package Service;

import Client.Client;
import GUI.showMessageFrame;
import Monitor.ClientThread;
import Utils.PacketUtils;
import Utils.ThreadManage;
import org.json.JSONObject;

import java.io.IOException;
import java.net.DatagramSocket;

/**
 * The type Login in.
 *
 * @author dzr
 * @version 1.0
 */
public class LoginIn {
    /**
     * The constant LOGIN_IN.
     */
    public static final int LOGIN_IN = 1;
    /**
     * The constant USER_NULL.
     */
    public static final int USER_NULL = 404;
    /**
     * The constant PWD_WRO.
     */
    public static final int PWD_WRO = 303;
    /**
     * The constant LOGIN_SUC.
     */
    public static final int LOGIN_SUC = 666;

    /**
     * Login in.
     *
     * @param uid      the uid
     * @param password the password
     * @param client   the client
     * @return the result of login in
     * @throws IOException the io exception
     */
    public static boolean loginIn(int uid, String password, DatagramSocket client) throws IOException {
        boolean res = false;
        JSONObject ret2Server = new JSONObject();
        ret2Server.put("cmd", LOGIN_IN);
        ret2Server.put("uid", uid);
        ret2Server.put("pwd", password);

        PacketUtils.sendPacket(ret2Server);
        JSONObject msg = PacketUtils.receivePacket();

        int ret_code = msg.getInt("ret_code");
        switch (ret_code){
            case LOGIN_SUC:{
                res = true;
                ClientThread clientThread = new ClientThread(uid, msg.getString("username"), msg.getInt("profileID"), msg.getString("sex"), msg.getString("birthday"), client);
                ThreadManage.getInstance().addClientThread(uid, clientThread);
                RequestFriStatus.requestFriInfo(uid);
                clientThread.start();
                new showMessageFrame("登录成功");
                break;
            }
            case USER_NULL:{
                new showMessageFrame("用户名不存在");
                break;
            }
            case PWD_WRO:{
                new showMessageFrame("密码错误");
                break;
            }
            default:{
                break;
            }
        }
        return res;
    }
}
